package no.saiboten.tourbuilder.login;

import javax.servlet.http.HttpServletRequest;

import no.saiboten.tourbuilder.constants.ResourceConstants;
import no.saiboten.tourbuilder.user.User;
import no.saiboten.tourbuilder.user.UserStatus;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

@Controller
@RequestMapping("login")
public class LoginController {

	@Autowired
	LoginService loginService;

	@Autowired
	UserStatus userStatus;

	@RequestMapping(method = RequestMethod.GET)
	public String loginGet() {
		if (userStatus.isAuthenticated()) {
			return "loggedin";
		}
		return "login";
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView loginPost(HttpServletRequest request,
			@RequestParam String userName, @RequestParam String password) {

		ModelAndView mav = new ModelAndView("login");

		User user = loginService.login(userName, password);

		if (user == null) {
			mav.addObject("result", "User not found/Incorrect password");
			mav.addObject("authLevel", AuthorizationLevel.NO_ACCESS);
			return mav;
		}
		request.getSession().setAttribute("user", user);
		RedirectView redirectView = new RedirectView(
				ResourceConstants.DEFAULT_STARTPAGE);
		mav.setView(redirectView);
		return mav;
	}
}
